package com.graduationdesign.zengyan.graduationdesignapp.ui.activities.search;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.graduationdesign.zengyan.graduationdesignapp.R;
import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.model.User;
import com.graduationdesign.zengyan.graduationdesignapp.ui.activities.PresenterInjection;
import com.graduationdesign.zengyan.graduationdesignapp.ui.activities.UiInjection;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.BaseActivity;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.BaseUiView;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.commonAdapter.CommonAdapter;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.commonAdapter.base.ViewHolder;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.errorhandle.BaseErrorView;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.errorhandle.CommonErrorView;
import com.graduationdesign.zengyan.graduationdesignapp.ui.contact.ProfileContact;
import com.graduationdesign.zengyan.graduationdesignapp.ui.presenter.ProfilePresenter;
import com.graduationdesign.zengyan.graduationdesignapp.utils.ViewAnimation;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity implements ProfileContact.ShowSearchUsers {

    private EditText et_search;
    private ImageButton bt_clear, bt_back;

    private BaseUiView progress_bar;
    private RelativeLayout lyt_no_result;

    private RecyclerView recyclerSuggestion;
    private AdapterSuggestionSearch mAdapterSuggestion;
    private LinearLayout lyt_suggestion;

    private ProfileContact.Presenter presenter;
    private CommonAdapter<User> userCommonAdapter;
    private List<User> mUserList = new ArrayList<>();



    @Override
    protected int provideLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected Boolean isFullScreen() {
        return true;
    }

    @Override
    protected void initArgument() {

    }

    @Override
    protected void initPresenter() {
        progress_bar = (BaseUiView) findViewById(R.id.base_ui);
        BaseErrorView errorView = new CommonErrorView(this);
        presenter = PresenterInjection.provideProfilePresenter(
                ProfilePresenter.newBuilder()
                    .setBaseErrorView(errorView)
                    .setMLoadingView(null)
                    .setShowSearchUsers(this)
        );
    }

    @Override
    protected void initToolbar() {
    }

    @Override
    protected void initView() {
        initRecyclerView();


        lyt_no_result =  findViewById(R.id.lyt_no_result);

        lyt_suggestion = (LinearLayout) findViewById(R.id.lyt_suggestion);
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.addTextChangedListener(textWatcher);

        bt_clear = (ImageButton) findViewById(R.id.bt_clear);
        bt_back = (ImageButton) findViewById(R.id.bt_back);
        bt_clear.setVisibility(View.GONE);
        recyclerSuggestion = (RecyclerView) findViewById(R.id.recyclerSuggestion);

        recyclerSuggestion.setLayoutManager(new LinearLayoutManager(this));
        recyclerSuggestion.setHasFixedSize(true);

        //set data and list adapter suggestion
        mAdapterSuggestion = new AdapterSuggestionSearch(this);
        recyclerSuggestion.setAdapter(mAdapterSuggestion);
        showSuggestionSearch();
        mAdapterSuggestion.setOnItemClickListener(new AdapterSuggestionSearch.OnItemClickListener() {
            @Override
            public void onItemClick(View view, String viewModel, int pos) {
                et_search.setText(viewModel);
                ViewAnimation.collapse(lyt_suggestion);
                hideKeyboard();
                searchAction();
            }
        });

        bt_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_search.setText("");
            }
        });

        bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        et_search.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideKeyboard();
                searchAction();
                return true;
            }
            return false;
        });

        et_search.setOnTouchListener((view, motionEvent) -> {
            showSuggestionSearch();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            return false;
        });
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setNestedScrollingEnabled(false);
        userCommonAdapter = new CommonAdapter<User>(this, R.layout.item_people, mUserList) {
            @Override
            protected void convert(ViewHolder holder, User user, int position) {
                holder.setText(R.id.name, user.getName());
                holder.setText(R.id.description, user.getDescription());
                holder.setOnClickListener(R.id.ripple_layout, v -> {
                    User user1 = mUserList.get(position);
                    startActivity(UiInjection.provideProfile(SearchActivity.this, user1.getStudentNum()));
                });

            }
        };
        recyclerView.setAdapter(userCommonAdapter);
    }

    @Override
    protected void start() {

    }



    private void showSuggestionSearch() {
        mAdapterSuggestion.refreshItems();
        ViewAnimation.expand(lyt_suggestion);
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence c, int i, int i1, int i2) {
            if (c.toString().trim().length() == 0) {
                bt_clear.setVisibility(View.GONE);
            } else {
                bt_clear.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence c, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    private void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void searchAction() {
        ViewAnimation.collapse(lyt_suggestion);
        lyt_no_result.setVisibility(View.GONE);

        final String query = et_search.getText().toString().trim();
        if (!query.equals("")) {
            mAdapterSuggestion.addSearchHistory(query);
            presenter.searchUser("201430098034",query);
        } else {
            Toast.makeText(this, "Please fill search input", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showSearchUsers(List<User> list) {
        mUserList.clear();
        if (list.isEmpty()) {
            lyt_no_result.setVisibility(View.VISIBLE);
            userCommonAdapter.notifyDataSetChanged();
            return;
        }
        lyt_no_result.setVisibility(View.GONE);
        mUserList.addAll(list);
        userCommonAdapter.notifyDataSetChanged();
    }
}
